<script setup lang="ts">
import {chatInfoStore} from "@/store/modules/chatInfo";
import {webSocketStore} from "@/store/modules/webSocket";
import {UserMessage, WebSocketMessage} from "@/types/webSocketMessageTypes";
import {getFileImage} from "@/utils/fileUtils";
import {onMounted, onUpdated, ref} from "vue";
import {uploadFile} from "@/utils/uploadFileUtils";
import {WebSocketMessageType} from "@/enums/webSocketEnum";


const socketStore = webSocketStore();
const chatStore = chatInfoStore();
const content = ref('');
const showFileUploadPopup = ref(false);
const fileList = ref([] as File[]);
const chatPageContent = ref(null);

onMounted(() => {
  chatStore.chatUser.content = 0;
  toBottom();
});

onUpdated(() => {
  toBottom();
})

const toBottom = () => {
  chatPageContent.value.scrollTop = chatPageContent.value.scrollHeight;
}

const handleFileChange = (event: Event) => {
  const inputElement: HTMLInputElement = event.target as HTMLInputElement;
  if (inputElement.files.length > 0) {
    updateFiles(inputElement.files);
    showFileUploadPopup.value = true;
  }
}

const sendMessage = (pointerEvent: PointerEvent) => {
  const userMessage: UserMessage = {
    id: chatStore.userMessages.length,
    from: chatStore.chatUser.chatUserId,
    type: 'string',
    message: content.value,
    sendTime: '发送中',
    status: 'sending',
    progress: 0
  };
  const webSocketMessage: WebSocketMessage = {
    type: WebSocketMessageType.USER_MESSAGE,
    data: userMessage
  };
  userMessage.id = chatStore.userMessages.push(userMessage) - 1;
  socketStore.webSocketClient.ws.send(JSON.stringify(webSocketMessage));
  content.value = null;
};


const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  const files = event.dataTransfer.files;
  if (files.length > 0) {
    updateFiles(files)
    showFileUploadPopup.value = true
  }
}

// 处理粘贴事件
const handlePaste = (event: ClipboardEvent) => {
  const clipboardItems = event.clipboardData.items;
  clearFileList()

  // 遍历剪贴板内容
  for (let i = 0; i < clipboardItems.length; i++) {
    clipboardItems[i].getAsString(str => {
      console.log(str)
    })
    if (clipboardItems[i].kind === 'file') {
      const file = clipboardItems[i].getAsFile();
      fileList.value.push(file);
    }
  }

  if (fileList.value.length > 0) {
    // 阻止默认粘贴行为（避免文本框出现文件路径）
    event.preventDefault();
    showFileUploadPopup.value = true
  }
}

const clearFileList = () => {
  showFileUploadPopup.value = false;
  fileList.value.length = 0;
}

const updateFiles = (files: FileList) => {
  clearFileList()
  for (let i = 0; i < files.length; i++) {
    fileList.value.push(files.item(i))
  }
}

const upload = (files: FileList) => {
  showFileUploadPopup.value = false;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const userMessage: UserMessage = {
      id: chatStore.userMessages.length,
      from: chatStore.chatUser.chatUserId,
      type: 'file',
      message: file.name,
      sendTime: '发送中',
      status: 'sending',
      progress: 0
    };
    userMessage.id = chatStore.userMessages.push(userMessage) - 1;
    uploadFile(file, chatStore.userMessages[userMessage.id], (id: number, result: boolean) => {
      const message = chatStore.userMessages[id];
      if (result) {
        message.progress = 100;
        const webSocketMessage: WebSocketMessage = {
          type: WebSocketMessageType.USER_MESSAGE,
          data: message
        };
        socketStore.webSocketClient.ws.send(JSON.stringify(webSocketMessage));
      } else {
        message.status = 'fail';
      }
    })
  }
}

const setTextColor = (status: string): any => {
  switch (status) {
    case 'sending':
      return {color: 'mediumaquamarine'};
    case 'succeed':
      return {color: 'black'};
    case 'fail':
      return {color: 'red'};
  }
}

</script>

<template>
  <div id="chat-page-box" class="chat-page-box">
    <div class="chat-page-content" ref="chatPageContent">
      <van-row
          class="my-4"
          v-for="chatContent in chatStore.userMessages"
          :justify="chatContent.from === chatStore.chatUser.chatUserId ? 'start' : 'end'">
        <van-col span="12" class="chat-content-box" :id="chatContent.id">
          <p class="ip-text" :style="setTextColor(chatContent.status)">{{ chatContent.sendTime }}</p>
          <div class="ip-chat-content px-[6px] py-1">
            <svg-icon v-if="chatContent.type === 'file'" class="text-[25px] w-14"
                      :name="getFileImage(chatContent.message)"/>
            <p class="ip-chat-text">{{ chatContent.message }}</p>
          </div>
          <van-progress
              v-if="chatContent.type === 'file' && chatContent.status === 'sending'"
              :percentage="chatContent.progress"
              stroke-width="5"
              :show-pivot="false"
          />
        </van-col>
      </van-row>
    </div>
    <van-cell-group class="chat-input-box">
      <van-field
          v-model="content"
          autosize
          type="textarea"
          rows="1"
          center
          @dragover.prevent
          @drop="handleDrop"
          @keydown.ctrl.enter="sendMessage"
          @paste="handlePaste"
          class="input-box"
      >
        <template #left-icon>
          <input v-show="false" ref="chooseFileInput" type="file" multiple @change="handleFileChange">
          <van-button size="small" type="primary" @click="$refs.chooseFileInput.click()">文件</van-button>
        </template>
        <!--<template #input>-->
        <!--  <textarea id="van-field-4-input" rows="1" class="van-field__control" style="height: 50px;"/>-->
        <!--</template>-->
        <template #button>
          <van-button size="small" type="primary" @click="sendMessage">发送</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <!--<van-popup-->
    <!--    v-model:show="showFileUploadPopup"-->
    <!--    round-->
    <!--    closeable-->
    <!--    position="bottom"-->
    <!--    @closed="clearFileList"-->
    <!--    :style="{ height: '30%' }"-->
    <!--    teleport="#app"-->
    <!--&gt;-->
    <!--  <Upload :file-list="fileList" @close="closeUploadPopup"></Upload>-->
    <!--</van-popup>-->
    <FileUploadPopup
        v-model="showFileUploadPopup"
        :file-list="fileList"
        @upload="upload"
        @close="clearFileList"
    ></FileUploadPopup>
  </div>
</template>

<style lang="css" scoped>
.chat-page-box {
  display: flex;
  flex-direction: column;
  background-color: #f7f7f8;
  position: fixed;
  top: var(--van-nav-bar-height);
  bottom: var(--van-tabbar-height);
  left: 0;
  width: 100%;
}

.chat-page-content {
  overflow-y: auto;
  /* 当内容超过最大高度时，垂直滚动 */
}

.chat-page-content::-webkit-scrollbar {
  display: none;
}

.ip-text {
  font-size: smaller;
}

.ip-chat-content {
  background-color: white;
  border-radius: 6px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: left;
}

.ip-chat-text {
  font-size: large;
  word-break: break-all;
  /* 允许在单词内部换行 */
  white-space: pre-wrap;
  /* 显示回车效果且超长换行 */
}

.chat-input-box {
  margin-top: auto
}

:deep(.van-field__control) {
  background-color: aliceblue;
  border-radius: 5px;
}
</style>